package com.yxjx.duoxue.course;

import java.util.ArrayList;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.PageLoading;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMKeyword;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.utils.UIHelper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class CourseSearchActivity extends BaseActionBarActivity {
	
	private EditText mSearchBox;
	private ImageView mSearchClear;
	private int mLastSearchTextLength = 0;
	private SearchListAdapter mSearchListAdapter;
	private Context mContext;
	
	private static final int MSG_LOAD_HOTS_DONE = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setCustomActionBar(R.layout.head_course_search);
		setContentView(R.layout.fragment_course_search_list);
		mContext = this;

		UIHelper.setClickListener(mActionBar.getCustomView(), R.id.search_button, mClickListener);
		UIHelper.setClickListener(mActionBar.getCustomView(), R.id.button_clear, mClickListener);
		final View anchor = mActionBar.getCustomView();
		
		PageLoading.getSearchHistory(CourseSearchActivity.this);
		initSearchHistory();
		mSearchList.setVisibility(View.VISIBLE);
		searchListLoading.setVisibility(View.GONE);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				PageLoading.getHotKeywords(CourseSearchActivity.this);
				mHandler.sendMessage(mHandler.obtainMessage(MSG_LOAD_HOTS_DONE));
			}
		}).start();
		
		mSearchBox = (EditText) mActionBar.getCustomView().findViewById(R.id.search_box);
		mSearchClear = (ImageView) mActionBar.getCustomView().findViewById(R.id.button_clear);
		mSearchBox.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				int length = arg0.toString().length();
				// 判断是否现实推荐关键字
				if (mLastSearchTextLength == 0 && length > 0) {
					showSearchHistory(true);
				} else if (length == 0 && mLastSearchTextLength > 0) {
					showSearchHistory(false);
				}
				
				// 判断是否显示关键字删除按钮
				if (length > 0) {
					mSearchClear.setVisibility(View.VISIBLE);
				} else {
					mSearchClear.setVisibility(View.INVISIBLE);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				mLastSearchTextLength = arg0.toString().length();
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				
			}
		});
		
		mSearchBox.setOnEditorActionListener(new EditText.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					mClickListener.onClick(mActionBar.getCustomView().findViewById(R.id.search_button));
					return true;
				}
				return false;
			}
			
		});
	}

	private void initSearchHistory() {
		mSearchList = (YxListView) findViewById(R.id.search_history);
		searchListLoading = findViewById(R.id.search_history_loading);
		mSearchListAdapter = new SearchListAdapter();
		mSearchListAdapter.setDatas(Globals.getInstance(this).getSearchHistory());
		mSearchList.setAdapter(mSearchListAdapter);
		mSearchList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (mSearchListAdapter.getItemViewType(arg2) == SearchListAdapter.TYPE_CLEAR_ALL) {
					YxDataBase db = YxDataBase.getInstance(getApplicationContext());
					db.emptySearchHistory();
					Globals.getInstance(CourseSearchActivity.this).setSearchHistory(new ArrayList<String>());
					mSearchListAdapter.setDatas(new ArrayList<String>());
					StatHelper.addKVEvent(mContext, "event_search_clear");
				} else if (mSearchListAdapter.getItemViewType(arg2) == SearchListAdapter.TYPE_ITEM) {
					//TODO
					UIHelper.setText(((EditText) mActionBar.getCustomView()
							.findViewById(R.id.search_box)), UIHelper.getText(
							arg1, R.id.text));
					// simulate onClick
					StatHelper.addKVEvent(mContext, "event_search_history_click",
							StatHelper.KEY_KEYWORD, UIHelper.getText(
									arg1, R.id.text));
					mClickListener.onClick(mActionBar.getCustomView().findViewById(R.id.search_button));
				}
				
			}
		});
	}

	private void initSearchHots() {
		searchHots = (GridView) findViewById(R.id.hot_search_items);
		searchHotsLoading = findViewById(R.id.hot_search_items_loading);
		searchHots.setAdapter(new HotsAdapter());
		searchHots.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String text = UIHelper.getText(arg1, R.id.item);
				UIHelper.setText(((EditText) mActionBar.getCustomView()
						.findViewById(R.id.search_box)), text);
				
				// simulate onClick
				StatHelper.addKVEvent(mContext, "event_search_hot_click",
						StatHelper.KEY_KEYWORD, text);
				mClickListener.onClick(mActionBar.getCustomView().findViewById(R.id.search_button));
			}
		});
	}
	
	private void showSearchHistory(boolean showHistory) {
		findViewById(R.id.hot_search_title).setVisibility(showHistory ? View.GONE : View.VISIBLE);
		findViewById(R.id.hot_search_items).setVisibility(showHistory ? View.GONE : View.VISIBLE);
	}
	
	class HotsAdapter extends BaseAdapter {
		private static final int MAX_SHOWN = 9;
		private ArrayList<DMKeyword> mHotWords = Globals.getInstance(CourseSearchActivity.this).getKeywords();

		@Override
		public int getCount() {
			if (mHotWords == null) {
				return 0;
			}
			return (mHotWords.size() > MAX_SHOWN) ? MAX_SHOWN : mHotWords.size();
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_grid_hot_search, null);
			} else {
				ret = arg1;
			}
			UIHelper.setText(ret, R.id.item, mHotWords.get(arg0).getWord());
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.search_button:
				String text = UIHelper.getEditText(mActionBar.getCustomView(), R.id.search_box);
				Intent intent = new Intent(getApplicationContext(), CourseListActivity.class);
				intent.putExtra(Yx.EXTRA_SEARCH_KEY_WORDS, text);

				if (!UIHelper.isEmpty(text)) {
					// 添加到内存
					Globals.getInstance(CourseSearchActivity.this).addSearchHistoryItem(text);
					mSearchListAdapter.notifyDataSetChanged();
					// 写到db
					YxDataBase db = YxDataBase.getInstance(getApplicationContext());
					db.insertSearchHistory(text);
				}
				StatHelper.addKVEvent(mContext, "event_search_input_keyword",
						StatHelper.KEY_KEYWORD, text);
				UIHelper.LoadingActivity(CourseSearchActivity.this, intent);
				break;
			case R.id.button_clear:
				mSearchBox.setText("");
				break;
			default:
				break;
			}
		}
	};
	private YxListView mSearchList;
	private View searchListLoading;
	private View searchHotsLoading;
	private GridView searchHots;
	
	class SearchListAdapter extends BaseAdapter {
		
		private ArrayList<String> mDatas = new ArrayList<String>();
		
		public static final int TYPE_ITEM = 0;
		public static final int TYPE_CLEAR_ALL = 1;
		public static final int TYPE_NO_ITEM = 2;
		public static final int TYPE_COUNT = 3;

		@Override
		public int getCount() {
			if (mDatas == null || mDatas.size() == 0) {
				return 1;
			}
			return mDatas.size() + 1;
		}
		
		@Override
		public int getViewTypeCount() {
			return TYPE_COUNT;
		};
		
		@Override
		public int getItemViewType(int position) {
			if (mDatas == null || mDatas.size() == 0) {
				return TYPE_NO_ITEM;
			} else if (position == getCount() - 1) {
				return TYPE_CLEAR_ALL;
			} else {
				return TYPE_ITEM;
			}
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = arg1;
			if (getItemViewType(arg0) == TYPE_NO_ITEM) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_city_name, null);
				} else {
					ret = arg1;
				}
				UIHelper.setText(ret, R.id.text, "搜索历史为空");
			} else if (getItemViewType(arg0) == TYPE_CLEAR_ALL) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_empty_history, null);
				} else {
					ret = arg1;
				}
				UIHelper.setText(ret, R.id.text, "清空搜索历史");
			} else {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_search_history, null);
				} else {
					ret = arg1;
				}
				UIHelper.setText(ret, R.id.text, mDatas.get(arg0));
			}
			
			return ret;
		}
		
		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public ArrayList<String> getDatas() {
			return mDatas;
		}

		public void setDatas(ArrayList<String> mDatas) {
			this.mDatas = mDatas;
			notifyDataSetChanged();
		}

	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_LOAD_HOTS_DONE:
				initSearchHots();
				searchHots.setVisibility(View.VISIBLE);
				searchHotsLoading.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		};
	};

}
